package com.jkd.controller;

import com.jkd.model.pojo.Student;
import com.jkd.service.IStudentService;
import com.jkd.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/service/login")
public class LoginController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String stuNum =  req.getParameter("stuNum");
    String password = req.getParameter("password");
//    String out = req.getParameter("out");

        IStudentService studentService = new StudentServiceImpl();
        Student student = studentService.selectByStuNum(stuNum);
        HttpSession session = req.getSession();
        String error = null ;
        //忘记密码
        String forget = req.getParameter("forget");
        System.out.println(forget+"*");
        if("1".equals(forget)){
           req.getRequestDispatcher("/WEB-INF/jsp/forget.jsp").forward(req,resp);
           return;
        }

        if(null != student){
            if(student.getPassword().equals(password)){
                String isRemember = req.getParameter("isRemember");
                System.out.println(isRemember);
                //实现记住密码的功能，将用户的账号和密码放入cookie
                if("on".equals(isRemember)){
                    Cookie cookie = new Cookie("userName",stuNum);
                    Cookie cookie1 =  new Cookie("password",password);
                    cookie.setPath("/");
                    cookie1.setPath("/");
                    cookie.setMaxAge(10);
                    cookie1.setMaxAge(10);
                    resp.addCookie(cookie);
                    resp.addCookie(cookie1);
                    req.getSession().setAttribute("checked",isRemember);
                }else{
                    Cookie cookie = new Cookie("userName","");
                    Cookie cookie1 =  new Cookie("password","");
                    cookie.setPath("/");
                    cookie1.setPath("/");
                    cookie.setMaxAge(10);
                    cookie1.setMaxAge(10);
                    resp.addCookie(cookie);
                    resp.addCookie(cookie1);
                }
                session.setAttribute("student",student);
                req.getRequestDispatcher("/service/student/index").forward(req,resp);
                return;
            }else{
                error = "1";
                req.setAttribute("error",error);
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
                return;
            }
        }
//        else if(out != null){
//            resp.sendRedirect("/jkd/index.jsp");
//        }
        else {
            error = "0";
            req.setAttribute("error",error);
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
